package com.ticket.web.controller.common;

import com.alibaba.fastjson2.JSON;
import com.ticket.common.constant.Constants;
import com.ticket.common.core.domain.AjaxResult;
import com.ticket.common.core.redis.RedisCache;
import com.ticket.common.utils.IDGenerator;
import com.ticket.common.utils.http.HttpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 *
 * @date: 2019-08-21 16:44
 */
@RestController
@RequestMapping("/sms/forAllUser")
@Api(description = "验证码管理")
public class SmsController {
    private Logger logger = LoggerFactory.getLogger(SmsController.class);
    @Value("${aliyun.send.url}")
    public String sendUrl;
    @Value("${aliyun.apikey.key}")
    public String key;

    @Autowired
    private RedisCache redisCache;

    @RequestMapping(value = "/sendCode", method = RequestMethod.GET)
    @ApiOperation("发送验证码")
    @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", dataTypeClass = String.class)
    public AjaxResult sendCode(String phone) {
        try {
            String verCode = IDGenerator.getFourRandom();//生位四位短信码
            logger.debug("sendCode phone:{} verCode:{}",phone, verCode);
            Map<String, String> params = new HashMap<String, String>();
            params.put("apikey", key);
            params.put("mobile", phone);
            params.put("text", "验证码" + verCode + "，用于手机号验证登录，3分钟内有效。请勿将验证码透露给他人。");
            String responseText = HttpUtils.post(sendUrl, params);
            logger.info("responseText:{}", responseText);
            if (JSON.parseObject(responseText).getString("code").equals("0")) {
                redisCache.setCacheObject(Constants.SMSCODE_CODE_KEY + phone, verCode, 180, TimeUnit.SECONDS);
                return AjaxResult.success("发送成功！");
            } else {
                return AjaxResult.error(JSON.parseObject(responseText).getString("msg"));
            }
        } catch (Exception e) {
            logger.error("发送失败:",e);
            return AjaxResult.error("发送失败");
        }
    }

    @RequestMapping(value = "/checkCode", method = RequestMethod.GET)
    public AjaxResult checkCode(String phone, String code) {
        String smsCode = redisCache.getCacheObject(Constants.SMSCODE_CODE_KEY + phone);
        logger.info("phone:{} code:{} redisCode:{}", phone, code, smsCode);
        if (!StringUtils.isEmpty(smsCode) && smsCode.equals(code)) {
            redisCache.deleteObject(Constants.SMSCODE_CODE_KEY + phone);
            return AjaxResult.success("校验成功！");
        } else {
            return AjaxResult.error("校验失败");
        }
    }
}